﻿using CKS.Core.Framework;
using CKS.PLC.Core.Cache;
using FreeSql;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ZR.Model.Models.ProductionControl;

namespace CKS.PLC.Action.Subscription.OP120
{
    public class MergeCodeAction : SaveProcessingResults
    {
        /// <summary>
        /// 打标机保存数据订阅点
        /// </summary>
        /// <param name="_value"></param>
        public MergeCodeAction(DecodeValue _value) : base(_value)
        {

        }


        public override AfterSaveResult AfterSaved(SaveArg e)
        {
            var dict = new Dictionary<string, object>();
            var vt = conn.Select<CksVirtualTable>().Where(a => a.TableName == "OP120_Data_2_2").First();
            string productCode = e.RowData["ProductCode"].ToString();
            if (vt!=null && !productCode.IsEmpty())
            {
                var columnQuery = conn.Select<CksVirtualColumn>().Where(a => a.TableId == vt.Id).OrderBy(a => a.Sequence);
                var columns = columnQuery.ToList();
                var table = ServiceCommon.GetFreesqlTableInfo(vt, columns);
                string coverCode = e.RowData["CoverCode"].ToString();
               
                dict["ProductCode"] = e.RowData["ProductCode"];
                dict["MarkTime"] = e.RowData["CreatedTime"].ToDate().ToString("yyyy-MM-dd HH:mm:ss");
                dict["CoverCode"] = coverCode;
                dict["JudgeResult"] = "2";
                dict["BottomPlateCode"] = string.Empty;
                dict["MergeTime"] = string.Empty;
                dict["CreatedTime"] = DateTime.Now;
                //从OP_70查询数据
                string startTime = DateTime.Now.AddDays(-60).ToString("yyyy-MM-dd HH:mm:ss");
                string endTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                var fdic  =  GetDynamicTableFirstData("OP70_Data", $" CreatedTime BETWEEN '{startTime}' AND '{endTime}' AND  CoverCode = @CoverCode ", new { CoverCode = coverCode });
                if(fdic!=null && fdic.Keys.Count>0)
                {
                    string bottomPlateCode = fdic["BottomPlateCode"].ToString();
                    dict["BottomPlateCode"] = bottomPlateCode;
                    dict["MergeTime"] = fdic["CreatedTime"].ToDate().ToString("yyyy-MM-dd HH:mm:ss");
                    if(!bottomPlateCode.IsEmpty() && !coverCode.IsEmpty() )
                    {
                        dict["JudgeResult"] = "1";
                    }
                }
                object obj = table.CreateInstance(dict);
                conn.Insert<object>().AsType(table.Type).AppendData(obj).ExecuteIdentity();
            }
            
            return base.AfterSaved(e);
        }


    }
}
